package com.zzf.concurrent.example.design.pattern.immutable;

import lombok.extern.slf4j.Slf4j;

/**
 * @author GaoFeng2017
 * @date 2019/9/7 15:55
 */
@Slf4j
public class ImmutableExample {

    public static void main(String[] args) throws InterruptedException {
        // immutableObjectTest();
        // syncObjectTest();
        // immutableObjectMultiThreadTest();
        // syncObjectMultiThreadTest();
    }

    private static void immutableObjectTest() {
        ImmutableObject immutableObject = new ImmutableObject("123", 1);
        long beginTime = System.currentTimeMillis();

        for (int i = 0; i < 1000000; i++) {
            log.info(immutableObject.toString());
        }

        log.info("finish, total time is {}", System.currentTimeMillis() - beginTime);
    }

    private static void syncObjectTest() {
        SynchronizeObject synchronizeObject = new SynchronizeObject("123", 1);
        long beginTime = System.currentTimeMillis();

        for (int i = 0; i < 1000000; i++) {
            log.info(synchronizeObject.toString());
        }

        log.info("finish, total time is {}", System.currentTimeMillis() - beginTime);
    }

    private static void immutableObjectMultiThreadTest() throws InterruptedException {
        long beginTime = System.currentTimeMillis();

        Thread t1 = new Thread(ImmutableExample::immutableObjectTest);
        Thread t2 = new Thread(ImmutableExample::immutableObjectTest);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        log.info("thread is terminated total time is {}", System.currentTimeMillis() - beginTime);
    }

    private static void syncObjectMultiThreadTest() throws InterruptedException {
        long beginTime = System.currentTimeMillis();

        Thread t1 = new Thread(ImmutableExample::syncObjectTest);
        Thread t2 = new Thread(ImmutableExample::syncObjectTest);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        log.info("thread is terminated total time is {}", System.currentTimeMillis() - beginTime);
    }
}
